<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/6/11
 * Time: 上午11:02
 */

namespace Modules\Admin\Auth\Controllers;

use App\Http\Controllers\Controller;
use App\Models\AdminOperationRecord;
use Illuminate\Http\Request;
use Modules\Admin\Auth\Facades\AdminAuth;
use App\Sms;

class LoginController extends Controller
{
    public function index(Request $request)
    {
        $url = $request->input('redirect_url', '/admin');
        return view('admin.auth::login', ['redirect_url' => $url]);
    }

    public function sendCode(Request $request)
    {
        $username = $request->input('username');
        $admin = AdminAuth::findByUserName($username);
        if($admin && isset($admin['mobile']) && !empty($admin['mobile'])){
            Sms::generate($admin['mobile'],Sms::TPL_LOGIN, $request->getClientIp());
            return success();
        }
        return fail(400,'用户不存在或管理员尚未绑定手机');

    }

    public function login(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        $sms_code = $request->input('sms_code','');
        if (!$username OR !$password) {
            return fail('表单填写不完整');
        }

        if (!AdminAuth::attempt($username, $password,$sms_code)) {
            return fail(400, '账号或密码或验证码不正确');
        }

        $this->recordAction('登录成功');

        return success();
    }

    public function logout(Request $request)
    {
        AdminAuth::logout();
        return redirect()->route('admin_login', ['redirect_url' => $request->server('HTTP_REFERER')]);
    }

    public function changePassword(Request $request)
    {
        $oldPass = $request->input('old_pass');
        $newPass = $request->input('new_pass');
        $checkPass = $request->input('check_pass');

        if (!$oldPass OR !$newPass) {
            return fail(400, '请输入密码');
        }

        if ($newPass != $checkPass) {
            return fail(400, '两次输入的密码不一致');
        }

        if (AdminAuth::changePassword($oldPass, $newPass)) {
            $this->recordAction('修改了密码');
            return success();
        } else {
            return fail(400, '旧密码不正确');
        }
    }
}